<?php

namespace app\index\controller;

use app\model\Customer as CustomerModel;
use app\index\middleware\Auth;

class Customer extends CustomerBase
{
    protected $middleware = [Auth::class];

    public function create()
    {
        $param = request()->param();

        $model = CustomerModel::where(['company_name' => $param['companyName']])->with('follow')->findOrEmpty();

        if ($model->isEmpty()) {
            $param['salesId'] = request()->user->id;
            $model = CustomerModel::create($param);
        } else {
            if ($model->follow) {
                if ($model->follow->statusValue === '1') {
                    return json(['code' => 40000, 'msg' => '客户报备中，请勿重复操作']);
                } else if ($model->follow->statusValue === '3') {
                    return json(['code' => 40000, 'msg' => '客户已签约，请勿重复操作']);
                }
            }
        }

        if (!$model) {
            return json(['code' => 40400, 'msg' => '新增失败']);
        }

        return json(['code' => 20000, 'msg' => '新增成功', 'data' => ['customer' => $model]]);
    }

    public function statistics()
    {
        $where['sales_id'] = request()->user->id;
        $where['province_id'] = input('provinceId');

        $data['Reporting'] = CustomerModel::where($where)->hasWhere('follow', ['status_value' => '1'])->count();
        $data['Terminated'] = CustomerModel::where($where)->hasWhere('follow', ['status_value' => '2'])->count();
        $data['Signed'] = CustomerModel::where($where)->hasWhere('follow', ['status_value' => '3'])->count();
        $data['Represented'] = CustomerModel::where($where)->hasWhere('follow', ['status_value' => '4'])->count();
        $data['SignedNotRepresented'] = CustomerModel::where($where)->hasWhere('follow', ['status_value' => '5'])->count();

        return json(['code' => 20000, 'data' => $data]);
    }
}
